package com.ivncorp.evnproject.upload;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.widget.Toast;

import com.hintdesk.core.utils.JSONHttpClient;
import com.ivncorp.evnproject.R;
import com.ivncorp.evnproject.api.RestAPI;
import com.ivncorp.evnproject.model.ObjectTuTT;
import com.ivncorp.evnproject.model.UploadTable;

public class MyServiceTuTT extends Service implements IUploadCompleteTuTT {
	private List<ObjectTuTT> uploadedFiles;
	private List<ObjectTuTT> result;
	private UploadFilesCompleteListener uploadFilesCompleteListener;

	@Override
	public void setUploadFilesCompleteListener(
			UploadFilesCompleteListener uploadFilesCompleteListener) {
		this.uploadFilesCompleteListener = uploadFilesCompleteListener;
	}

	// Binder cho cac client
	private final IBinder mBinder = new LocalBinderTuTT();

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	public void uploadFiles(List<ObjectTuTT> files) {
		this.uploadedFiles = files;
		new UploadFilesTask().execute();
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public class LocalBinderTuTT extends Binder {
		public MyServiceTuTT getService() {
			return MyServiceTuTT.this;

		}
	}

	class UploadFilesTask extends AsyncTask<Void, Integer, Integer> {
		Integer totalCount = 0;
		Builder mBuilder;
		NotificationManager mNotifyManager;
		int id = 1;

		@Override
		protected void onPreExecute() {

			mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			mBuilder = new NotificationCompat.Builder(getApplicationContext());
			mBuilder.setContentTitle("Upload").setContentText("Uploading...")
					.setSmallIcon(R.drawable.ic_launcher);
			mBuilder.setProgress(100, 0, false);
			// Displays the progress bar for the first time.
			mNotifyManager.notify(id, mBuilder.build());
		}

		@Override
		protected Integer doInBackground(Void... params) {
			Integer uploadCount = 0;
			totalCount = uploadedFiles.size();
			result = new ArrayList<ObjectTuTT>();
			for (int index = 0; index < uploadedFiles.size(); index++) {
				ObjectTuTT objectTable = uploadedFiles.get(index);
				ObjectTuTT objectResult = new ObjectTuTT();
				objectResult.setCode(objectTable.getCode());
				objectResult.setName(objectTable.getName());
				objectResult.setUploaded(objectTable.getUploaded());
				objectResult.setId_object(objectTable.getId_object());

				// General
				String pathGeneral = objectTable.getImage_1();
				if (!pathGeneral.isEmpty()) {
					File file = new File(pathGeneral);
					String name = file.getName();
					JSONHttpClient jsonHttpClient = new JSONHttpClient();
					HDFile[] hdFiles = null;
					try {
						hdFiles = jsonHttpClient.PostFile(
								ServiceUrl.REST_SERVICE_URL, "1", file, name,
								HDFile[].class);
					} catch (Exception e) {
						// TODO: handle exception
					}
					if (hdFiles != null && hdFiles.length == 1) {
						uploadCount++;
						publishProgress((int) (((float) uploadCount / totalCount) * 100));
						objectResult.setImage_1(hdFiles[0].getUrl());
					}
				}

				result.add(objectResult);

				UploadTable uploadtable = new UploadTable();

				uploadtable.setName(objectResult.getName());
				uploadtable.setCode(objectResult.getCode());
				uploadtable.setImage1(objectResult.getImage_1());

				ExifInterface exif;
				try {

					exif = new ExifInterface(objectTable.getImage_1());
					float[] LatLong = new float[2];
					exif.getLatLong(LatLong);
					float latitude = LatLong[0];
					float longitude = LatLong[1];
					uploadtable.setLatitude(Double.toString(latitude));
					uploadtable.setLongitude(Double.toString(longitude));

				} catch (IOException e) {
					Toast.makeText(getApplication(), "Eror set GPS",
							Toast.LENGTH_SHORT).show();
				}
				new AsyncCreateUploadTable().execute(uploadtable);
			}

			return uploadCount;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			mBuilder.setProgress(100, (int) (progress[0]), false);
			// Displays the progress bar for the first time.
			mNotifyManager.notify(id, mBuilder.build());
		}

		@Override
		protected void onPostExecute(Integer uploadCount) {

			UploadErrorCode errorCode = UploadErrorCode.OK;
			if (uploadCount == 0)
				errorCode = UploadErrorCode.Failed;
			else if (uploadCount < totalCount) {
				errorCode = UploadErrorCode.PartlySuccessful;
				mBuilder.setContentText("Upload PartlySuccessful")
				// Removes the progress bar
						.setProgress(0, 0, false);
				mNotifyManager.notify(id, mBuilder.build());
			} else if (uploadFilesCompleteListener != null) {
				mBuilder.setContentText("Upload complete")
				// Removes the progress bar
						.setProgress(0, 0, false);
				mNotifyManager.notify(id, mBuilder.build());
				uploadFilesCompleteListener.onCompleted(errorCode);
			}

		}
	}

	protected class AsyncCreateUploadTable extends
			AsyncTask<UploadTable, JSONObject, JSONObject> {

		@Override
		protected JSONObject doInBackground(UploadTable... params) {

			RestAPI api = new RestAPI();
			JSONObject result = null;
			try {
				result = api.AddTuTrungThe(params[0].getName(),
						params[0].getCode(), params[0].getImage1(),
						params[0].getLatitude(), params[0].getLongitude());

			} catch (Exception e) {
				// Log.d("upload", e.getMessage());
			}
			return result;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}

	}

	@Override
	public List<ObjectTuTT> getList() {
		// TODO Auto-generated method stub
		return result;
	}

}